package com.wwm.springcloud.authservice.service.extend;

import com.wwm.springcloud.authservice.bean.SaltedUser;
import com.wwm.springcloud.authservice.bean.PortalUser;
import com.wwm.springcloud.authservice.service.IAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 自定义userDetailsService,取用户数据
 * @author wuwanming
 */
@Component
public class DbUserDetailsService implements UserDetailsService
{
    private static Logger logger = LoggerFactory.getLogger(DbUserDetailsService.class);

    @Resource(name = "accountService")
    private IAccountService accountService;

    /**
     * 根据用户名获取用户 - 用户的角色、权限等信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        UserDetails userDetails = null;
        PortalUser user=new PortalUser();
        try
        {
            user = accountService.getUserInfo(username);

            Collection<GrantedAuthority> authList = getAuthorities();
            userDetails = new SaltedUser(username, user.getPassword(), true, true, true, true, authList, user.getUuid());
        }
        catch (Exception e)
        {
            logger.error(e.getMessage());
        }
        return userDetails;
    }

    /**
     * 获取用户权限
     *
     * @return 用户权限
     */
    private Collection<GrantedAuthority> getAuthorities()
    {
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();
        authList.add(new SimpleGrantedAuthority("ROLE_USER"));
        authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        return authList;
    }
}
